#include "videowidget.h"

VideoWidget::VideoWidget(QWidget *parent) : QWidget(parent)
{
    mVideoWidget = new QVideoWidget(this);
    mPlayer = new QMediaPlayer;
    mPlayer->setVideoOutput(mVideoWidget);    //设置视频输出显示位置

    //设置视频外的背景为黑色
    mVideoWidget->setAutoFillBackground(true);
    QPalette palette(QPalette::Window, QColor(0,0,0));
    mVideoWidget->setPalette(palette);

    connect(mPlayer,SIGNAL(stateChanged(QMediaPlayer::State)),this,SLOT(OnStateChanged(QMediaPlayer::State)));
    connect(mPlayer,SIGNAL(positionChanged(qint64)),this,SIGNAL(positionChanged(qint64)));
    connect(mPlayer,SIGNAL(durationChanged(qint64)),this,SIGNAL(durationChanged(qint64)));
}

VideoWidget::~VideoWidget()
{
    delete mPlayer;
    delete mVideoWidget;
}

void VideoWidget::init()
{

}

void VideoWidget::setVideoName(QString name)
{
    mPlayer->setMedia(QUrl::fromLocalFile(name));  //给播放器设置视频路劲
    videoName = name;
}
QString VideoWidget::getVideoName()
{
    return videoName;
}

bool VideoWidget::play()
{
    if(videoName.isEmpty())
        return 0;
    mPlayer->play();
    return 1;
}
bool VideoWidget::pause()
{
    if(mState != QMediaPlayer::PlayingState)
        return 0;
    mPlayer->pause();
    return 1;
}
bool VideoWidget::stop()
{
    if(mState == QMediaPlayer::StoppedState)
        return 0;
    mPlayer->stop();
    return 1;
}

void VideoWidget::setPlaySpeed(double speed)
{
    mPlayer->setPlaybackRate(speed);    //设置播放速度
}

quint64 VideoWidget::getDuration()
{
    return mPlayer->duration();
}
bool VideoWidget::setPlayPos(quint64 position)
{
    if(mState == QMediaPlayer::StoppedState)
        return 0;
    mPlayer->setPosition(position);
    return 1;
}
quint64 VideoWidget::getCurrentPlyPos()
{
    return mPlayer->position(); //返回播放位置值
}

void VideoWidget::setVideoBackColor(QColor color)
{
    QPalette palette(QPalette::Window, color);
    this->setPalette(palette);
}

void VideoWidget::OnStateChanged(QMediaPlayer::State enumState)
{
    mState = enumState;     //获取状态
    emit stateChanged(enumState);   //对外发送状态
}

void VideoWidget::resizeEvent(QResizeEvent *event)
{
    mVideoWidget->setGeometry(0,0,this->width(),this->height());
}
